package com.lwq.lwqmicoservice.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.lwq.lwqmicoservice.common.model.Result;
import com.lwq.lwqmicoservice.framework.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/11/16
 */
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisUtil redis;

    public static final String Authorization = "Authorization";
    public static final String NO_LOGIN = "未登录,请登录";

    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入网关token过滤器");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        CorsConfiguration c = new CorsConfiguration();
        c.setAllowCredentials(true);
        String authorization = request.getHeaders().getFirst(Authorization);
        String path = request.getURI().getPath();
        if (StringUtils.isEmpty(authorization)) {
            return response.writeWith(Mono.just(response(true, response, NO_LOGIN)));
        }
        exchange.getRequest().getHeaders().add("user", authorization);
        return chain.filter(exchange);
    }

    private DataBuffer response(boolean isErr, ServerHttpResponse response, String msg) {
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONString(isErr ? Result.error(msg) : Result.ok()).getBytes(StandardCharsets.UTF_8));
        response.setStatusCode(isErr ? HttpStatus.BAD_REQUEST : HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return buffer;
    }
}
